package com.jsbs.iam.user.service.impl;

import com.jsbs.iam.common.core.utils.StringUtils;
import com.jsbs.iam.user.entity.IamPostBase;
import com.jsbs.iam.user.mapper.PostInfoMapper;
import com.jsbs.iam.user.param.PostInfoDto;
import com.jsbs.iam.user.param.PostInfoParam;
import com.jsbs.iam.user.service.PostInfoService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class PostInfoServiceImpl implements PostInfoService {
    @Autowired
    private PostInfoMapper postInfoMapper;


    @Override
    public void syncPostInfo(PostInfoParam postInfoParam) {
        if (CollectionUtils.isEmpty(postInfoParam.getPostInfoList())) {
            return;
        }
        // 新增岗位列表
        List<IamPostBase> postList = new ArrayList<>();
        // 更新列表
        List<IamPostBase> updateList = new ArrayList<>();
        // 岗位编码非空
        List<PostInfoDto> enableList = postInfoParam.getPostInfoList().stream().filter(item -> StringUtils.isNotEmpty(item.getPostId())).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(enableList)) {
            return;
        }
        enableList.forEach(item -> {
            IamPostBase postBase = new IamPostBase();
            BeanUtils.copyProperties(item, postBase);
            // 归属租户
            postBase.setCompanyCode(postInfoParam.getCompanyCode());
            // 归属组织类型
            postBase.setOrgTypeCode(postInfoParam.getDataSource());
            // 是否已存在
            if (postInfoMapper.countByCode(postInfoParam.getCompanyCode(), postInfoParam.getDataSource(), item.getPostId()) > 0) {
                updateList.add(postBase);
            } else {
                // 默认同步
                postBase.setSyncFlag(0);
                postList.add(postBase);
            }
        });
        // 批量新增
        if (CollectionUtils.isNotEmpty(postList)) {
            postInfoMapper.batchInsert(postList);
        }
        // 批量更新
        if (CollectionUtils.isNotEmpty(updateList)) {
            postInfoMapper.batchUpdate(updateList);
        }
    }
}
